package com.ruoyi.utils;


import com.ruoyi.utils.JxlsUtils;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ExcelExport {



    public static void exportByTemplate( String templateName,OutputStream out,Map<String,Object> params )throws IOException {
        org.springframework.core.io.Resource resource = new ClassPathResource("templates/"+templateName);
        InputStream in  = resource.getInputStream();
        export(in,out,params);
    }

    private static File watermarkFileName = null;
    private static FileInputStream fis = null;
    private static int width = 600; // 水印图片的宽度
    private static int height = 1020; // 水印图片的高度 因为设置其他的高度会有黑线，所以拉高高度

    public static void addWatermark(String xls_filePath_in, String xls_filePath_out, String watermarkText) throws Exception{
        InputStream is = new FileInputStream(new File(xls_filePath_in));
        jxl.Workbook wb = jxl.Workbook.getWorkbook(is); // 获得原始文档
        WritableWorkbook wwb = jxl.Workbook.createWorkbook(new File(xls_filePath_out), wb);
        WritableSheet ws1 = wwb.getSheet(0);// 得到工作薄中的第一个工作表
        Map map = createWaterMark1(watermarkText);
        File fileImg = (File) map.get("file");

        byte imageData[] = new byte[(int) fileImg.length()];
        FileInputStream fis = new FileInputStream(fileImg);
        fis.read(imageData);
       // ws1.setWaterMarkImage(imageData, (int)map.get("width"), (int)map.get("height"));

        wwb.write();
        wwb.close();
        fis.close();
    }

    public static File createWaterMark2(String watermark) throws IOException {
        int width = 800;
        int height = 1020;
        File file = new File("watermark.bmp");
        Font font = new Font("Serif", Font.ITALIC, 20);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        // 设置字体颜色为灰色
        g2.setColor(Color.LIGHT_GRAY);
        // 设置字体
        g2.setFont(font);
        // 设置字体倾斜度
        g2.rotate(Math.toRadians(0), (double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, width, height);
        FontRenderContext context = g2.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(watermark, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        g2.drawString(watermark, (int) x, (int) baseY);
        // ImageIO.write(bi, "bmp", file);
        // 通过bmp写入文件
        //BMPEncoder.write(bi, file);
        return file;
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map createWaterMark1(String watermarkMessage) throws IOException {
        Map map = new HashMap();
        File file = new File("watermark.bmp");

        // 获取bufferedImage对象
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 处理背景色，设置为 白色
        int minx = bi.getMinX();
        int miny = bi.getMinY();
        for (int i = minx; i < width; i++) {
            for (int j = miny; j < height; j++) {
                bi.setRGB(i, j, 0xffffff);
            }
        }

        // 获取Graphics2d对象
        Graphics2D g2d = bi.createGraphics();
        // 设置字体颜色为灰色
        g2d.setColor(Color.LIGHT_GRAY);
        // 设置图片的属性
        g2d.setStroke(new BasicStroke(1));
        // 设置字体
        g2d.setFont(new Font("Serif", Font.ITALIC, 40));
        // 设置字体倾斜度
        g2d.rotate(Math.toRadians(-8));

        // 写入水印文字 原定高度过小，所以累计写水印，增加高度
        for (int i = 1; i < 7; i++) {
            g2d.drawString(" :  " + watermarkMessage, 0, 180 * i + 40 * (i + 1));
        }
        // 设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放对象
        g2d.dispose();
        // 通过bmp写入文件
        // BMPEncoder.write(bi, file);
        ImageIO.write(bi, "bmp", file);
        map.put("file", file);
        map.put("width", width);
        map.put("height", height);

        return map;
    }

    /**
     * 生成水印图片
     * @param watermark
     * @return
     * @throws IOException
     */
    public static File createWaterMark(String watermark) throws IOException {
        // 获取bufferedImage对象
        BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        // 2.创建一个带透明色的BufferedImage对象
        bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        // 处理背景色，设置为 白色
        int minx = bi.getMinX();
        int miny = bi.getMinY();
        for (int i = minx; i < width; i++) {
            for (int j = miny; j < height; j++) {
                bi.setRGB(i, j, 0xffffff);
            }
        }
//		Font font = new Font("华文细黑", Font.ITALIC, 20);
        // 获取Graphics2d对象
        Graphics2D g2d = bi.createGraphics();
        // 设置字体颜色为灰色
        g2d.setColor(Color.LIGHT_GRAY);
        // 设置图片的属性
        g2d.setStroke(new BasicStroke(1));
        // 设置字体
        g2d.setFont(new Font("华文细黑", Font.ITALIC, 20));
        // 设置字体倾斜度
        g2d.rotate(Math.toRadians(-10), (double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
        // 写入水印文字 原定高度过小，所以累计写水印，增加高度

        for (int i = 1; i < 4; i++) {
            g2d.drawString(watermark, 100, 300 * i);
        }
        // 设置透明度
       // g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放对象
        g2d.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        String targetImagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"WaterMark";
        ImageIO.write(bi, "png", new File(targetImagePath));
        watermarkFileName = new File(targetImagePath);
        // 通过bmp写入文件
        //BMPEncoder.write(bi, watermarkFileName);

        return watermarkFileName;
    }


    public static void exportByTemplateSy( String templateName,OutputStream out,Map<String,Object> params )throws IOException {
        org.springframework.core.io.Resource resource = new ClassPathResource("templates/"+templateName);
        InputStream in  = resource.getInputStream();
        export(in,out,params);
    }
    /**
     * 添加水印 - 未实现功能 20220606 qh
     * @param templateName
     * @param out
     * @param params
     * @throws IOException
     */
    public static void exportByTemplateForSY( String templateName,OutputStream out,Map<String,Object> params )throws IOException {
        org.springframework.core.io.Resource resource = new ClassPathResource("templates/"+templateName);
        InputStream in  = resource.getInputStream();
//        FileInputStream fis = new FileInputStream(resource.getFile());
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        WaterMarkUtil.putWaterMarkToExcel(workbook);
//        InputStream in  = fis;
//        fis.close();
        export(in,out,params);
    }

    public static void export(InputStream in,OutputStream out,Map<String,Object> params) throws IOException {

        try {
            Context context = PoiTransformer.createInitialContext();
            params.forEach((key, value) -> {
                context.putVar(key, value);
            });

            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            jxlsHelper.setDeleteTemplateSheet(true);

            Transformer transformer = jxlsHelper.createTransformer(in, out);

            JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig()
                    .getExpressionEvaluator();

            Map<String, Object> funcs = new HashMap<String, Object>();

            funcs.put("utils", new JxlsUtils());

            JexlBuilder jb = new JexlBuilder();
            jb.namespaces(funcs);
            JexlEngine je = jb.create();

            evaluator.setJexlEngine(je);

            jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);

            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            in.close();
        }

    }

}
